<?php
/**
 * Created by PhpStorm.
 * User: yangjiaming
 * Date: 2018/2/4
 * Time: 22:00
 */

namespace Halo;

use Halo\Validator\ParamValidator;
use Halo\Validator\Request;

class Controller
{
    private $_view;
    private $_controller;
    private $_action;
    private $rule = [];
    private $validate = [];
    public function __construct($controller, $action)
    {
        $this->_controller = $controller;
        $this->_action = $action;
        $this->_view = new View($controller, $action);
    }

    public function display($tpl = '')
    {
        $this->_view->display($tpl);
    }

    public function assign($name, $value)
    {
        $this->_view->assign($name, $value);
    }
    public function getParams(array $required, array $optional = [])
    {
        $this->getRules($required, $optional);
        $request = $this->getRequest();

        return ParamValidator::paramsFromRequestAndRules($request, $this->rule, $this->validate);
    }
    public function getRules($required, $optional)
    {
        foreach ($required as $r) {
            $this->rule[$r] = true;
        }
        $optional = array_flip($optional);
        $this->rule = array_merge($this->rule, $optional);
    }
    public function getRequest()
    {
        return new Request();
    }
    public function validate($array, $type)
    {
        foreach ($array as $r) {
            $this->validate[$r] = $type;
        }
    }
    public function redirect($url)
    {
        $host = $_SERVER['HTTP_HOST'];
        header('Location: http://'.$host.$url);
    }
    public function success($message, $time='1000')
    {
        echo '<script src="/static/layui/layui.js"></script>';
        echo "<script>layui.use('layer', function(){
  var layer = layui.layer;
  
  layer.msg('{$message}', {icon: 1, time:'{$time}'});
}); </script>";
    }
    public function verifyLogin()
    {
        $login = new \Eagle\Service\LoginInfo();
        $data = $login->getUserEmail();
        if(!$data) {
            //$this->display('login');
            //exit();
        }
    }
    public function getPage()
    {
        return $this->getParams([], ['page', 'limit']);
    }
}